import {esri} from '../../api/esriAPI'

let TintLayer = null;

class BaiduMap {
  constructor() {

  }
  buildTintLayer(){
    if(!TintLayer){
      var {BaseTileLayer, Color, esriConfig, Map, MapView, SceneView, esriRequest} = esri;
      TintLayer = BaseTileLayer.createSubclass({
        properties: {
          urlTemplate: null,
          tint: {
            value: null,
            type: Color
          }

        },
        getTileUrl: function (level, row, col) {
          var zoom = level - 1;
          var offset = Math.pow(2, zoom);
          var offsetX = offset - 0;
          var offsetY = offset - 1;
          console.log("offset",offsetX,offsetY)
          var numX = col - offsetX;
          var numY = (-row) + offsetY;
          zoom = level + 1;
          var url = this.urlTemplate
            .replace("{z}", zoom)
            .replace("{x}", numX)
            .replace("{y}", numY);
          return url;
        },
        fetchTile: function (level, row, col) {
          var url = this.getTileUrl(level, row, col);
          return esriRequest(url, {
            responseType: "image",
            allowImageDataAccess: true
          }).then(function (response) {

            var image = response.data;
            var width = this.tileInfo.size[0];
            var height = this.tileInfo.size[0];

            var canvas = document.createElement("canvas");
            var context = canvas.getContext("2d");
            canvas.width = width;
            canvas.height = height;

            context.drawImage(image, 0, 0, width, height);

            return canvas;
          }.bind(this));
        }
      });
    }
  }

  create() {
    this.buildTintLayer();
    let tileLayer = new TintLayer({
      urlTemplate: "http://online1.map.bdimg.com/tile/?qt=tile&x={x}&y={y}&z={z}&styles=pl",
      title: "百度地图"
    });
    return tileLayer;
  }

  road(){
   this.buildTintLayer();
    let tileLayer = new TintLayer({
      urlTemplate: `http://its.map.baidu.com:8002/traffic/TrafficTileService?level={z}&x={x}&y={y}&time=${new Date().getTime()}`,
      title: "百度地图-路况"
    });
    // var url = "http://its.map.baidu.com:8002/traffic/TrafficTileService?level="+zoom+"&x="+numX+"&y="+numY+"&time=1537261665762";
    return tileLayer;
  }
}

export const baiduMap = new BaiduMap();
